package com.zodiac.app.szse.sse.stocklist;

import com.zodiac.app.szse.sse.SseClient;
import com.zodiac.app.szse.sse.stocklist.dto.SseStockListRequest;
import com.zodiac.app.szse.sse.stocklist.dto.SseStockListResponse;

import java.util.ArrayList;
import java.util.List;

/**
 * 上交所-股票列表-接口
 */
public class SseStockListApi {
    private static final String STOCK_LIST_QUERY_URL = "http://query.sse.com.cn/security/stock/downloadStockListFile.do";

    /**
     * 股票列表查询
     *
     * @param request
     * @return
     */
    public SseStockListResponse stockListQuery(SseStockListRequest request) {
        final String body = SseClient.create(STOCK_LIST_QUERY_URL).execute(request);
        final String[] rows = body.split(System.lineSeparator());

        final List<SseStockListResponse.Item> items = new ArrayList<>();
        final int length = rows.length;
        for (int i = 1; i < length; i++) {
            final String[] columns = rows[i].split("\\s+");
            final SseStockListResponse.Item item = new SseStockListResponse.Item();
            item.setCompanyCode(columns[0]);
            item.setCompanyShortName(columns[1]);
            item.setCode(columns[2]);
            item.setShortName(columns[3]);
            item.setListedDate(columns[4]);
            items.add(item);
        }

        final SseStockListResponse response = new SseStockListResponse();
        response.setItems(items);
        return response;
    }
}
